package main.social.web;

import javax.servlet.http.HttpServletRequest;

import main.social.entities.Entrys;
import main.social.service.EntryService;
import main.social.service.util.Utils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping(value = "/Upload.html")
public class ImageUploadController {
	EntryService entryService;
	
	public void setEntryService(EntryService entryService) {
		this.entryService = entryService;
	}

	@RequestMapping(method = RequestMethod.GET)
    public String getUploadForm(HttpServletRequest request) {
		if(request.getSession().getAttribute("LOGEDIN_USER") == null){
			return "redirect:Login";
		}
        return "Upload";
    }
	
	@RequestMapping(method = RequestMethod.POST)
	public String upload(@RequestParam("fileData") CommonsMultipartFile fileData,
			HttpServletRequest request){
		String username = request.getSession().getAttribute("LOGEDIN_USER").toString();
		Entrys newEntry = this.entryService.insertEntry(username);
		String saveName = Utils.EntryPath + "/" + newEntry.getUuid() + ".png";
		if (main.social.service.util.Utils.Savefile(fileData, saveName)){
			return "redirect:Home";
		}
		return "Upload";
	}
}
